package kuoge.practice.concurrent.aqs.injvm;

import lombok.SneakyThrows;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *  使用Semaphore来控制5个并发执行
 */
public class SemaphoreTest {
    private static final Semaphore semaphore = new Semaphore(5);
    private static final AtomicInteger currentCount = new AtomicInteger(0);

    @SneakyThrows
    public static String doAction() {
        semaphore.acquire();
        try {
            System.out.println("current count:" + currentCount.incrementAndGet());
            Thread.sleep(Duration.ofSeconds(2));
        } catch (InterruptedException e) {
            // ignore
        } finally {
            semaphore.release();
            currentCount.decrementAndGet();
        }
        return "";
    }

    @SneakyThrows
    public static void main(String[] args) {
        try (ExecutorService executorService = Executors.newFixedThreadPool(15)) {
            final List<Callable<String>> callableList = new ArrayList<>(15);
            for (int i = 1; i <= 15; i++) {
                callableList.add(SemaphoreTest::doAction);
            }
            executorService.invokeAll(callableList);
        }
    }
}
